package com.base.project.util

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.lifecycle.findViewTreeLifecycleOwner
import com.orange.common.ktx.doOnDestroy

/**
 * 动画工具类
 */
object AnimationUtils {

    /**
     * 放大||缩小动画
     */
    fun scale(
        view: View,
        scale: Float = 0.9f,
        duration: Long = 500,
        repeatCount: Int = ValueAnimator.INFINITE,
        startDelay: Long = 500
    ): Animator {
        val scaleX = ObjectAnimator.ofFloat(view, "scaleY", 1f, scale, 1f)
        val scaleY = ObjectAnimator.ofFloat(view, "scaleX", 1f, scale, 1f)

        scaleX.repeatCount = repeatCount
        scaleY.repeatCount = repeatCount

        val animatorSet = AnimatorSet()
        //插值器
        animatorSet.interpolator = LinearInterpolator()
        //动画时长
        animatorSet.duration = duration
        //延迟时长
        animatorSet.startDelay = startDelay
        animatorSet.playTogether(scaleX, scaleY)
        animatorSet.start()
        autoCancelAnimation(view, animatorSet)
        return animatorSet
    }

    /**
     *  指定view在两个view的中心点反复移动
     */
    fun translationViewToView(
        view: View,
        startView: View,
        endView: View,
        duration: Long = 500,
        repeatCount: Int = ValueAnimator.INFINITE,
        startDelay: Long = 0
    ): AnimatorSet {

        // 获取view 到另外两个view中心点的偏移量
        val startArray = ViewUtils.getToViewCentreXy(view, startView)
        val endArray = ViewUtils.getToViewCentreXy(view, endView)

        val translationX = ObjectAnimator.ofFloat(view, "translationX",startArray[0],endArray[0])
        val translationY = ObjectAnimator.ofFloat(view, "translationY", startArray[1],endArray[1])
        translationX.repeatCount = repeatCount
        translationY.repeatCount = repeatCount

        val animatorSet = AnimatorSet()
        //插值器
        animatorSet.interpolator = LinearInterpolator()
        //动画时长
        animatorSet.duration = duration
        //延迟时长
        animatorSet.startDelay = startDelay
        animatorSet.playTogether(translationX, translationY)
        animatorSet.start()
        autoCancelAnimation(view, animatorSet)
        return animatorSet
    }

    /**
     * Destroy 取消动画
     */
    private fun autoCancelAnimation(view: View, animator: Animator) {
        view.findViewTreeLifecycleOwner()?.lifecycle?.doOnDestroy {
            view.clearAnimation()
            animator.cancel()
        }
    }
}